import React, { Suspense, useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import Backprev from "../components/BackPrev";
import Loading from "../components/Loading";
import Tabbar from "../components/Tabbar/Tabbar";
import { useToastError } from "../hooks/useToast";
import EventBus from "../util/EventBus";

export default function App() {
  const error = useToastError();
  const nav = useNavigate();
  let token = localStorage.getItem("x-auth-token");
  useEffect(() => {
    if (!token) {
      // 弹出提示
      error("请先登录");
      // 跳转到login
      nav("/login");
    } else {
      nav("/home");
    }
  }, []);

  useEffect(() => {
    EventBus.on("error", (msg: string) => {
      error(msg);
    });

    EventBus.on("login_timeout", () => {
      // 1. 提示
      error("登录失效，请重新登录");
      // 3. 清空token
      localStorage.removeItem("x-auth-token");
      // 2. 跳转
      nav("/login");
    });
  }, []);
  // 条件渲染
  return token ? (
    <>
      <Suspense fallback={<Loading />}>
        <Outlet />
      </Suspense>
      <Tabbar />
      <Backprev />
    </>
  ) : (
    <></>
  );
}
